<template>
  <div class="permission-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>权限管理</h2>
    </div>

    <el-row :gutter="20">
      <!-- 左侧角色列表 -->
      <el-col :span="8">
        <el-card class="role-card">
          <div class="card-header">
            <span>角色列表</span>
            <el-button type="primary" size="small" @click="addRole">新增角色</el-button>
          </div>
          <el-table 
            :data="roleList" 
            style="width: 100%" 
            highlight-current-row
            @current-change="handleRoleChange"
          >
            <el-table-column prop="name" label="角色名称"></el-table-column>
            <el-table-column prop="userCount" label="用户数" width="80"></el-table-column>
            <el-table-column label="操作" >
              <template #default="scope">
                <el-button size="small" @click="editRole(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteRole(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 右侧权限配置 -->
      <el-col :span="16">
        <el-card class="permission-card">
          <div class="card-header">
            <span>权限配置 - {{ currentRole?.name || '请选择角色' }}</span>
            <el-button type="primary" size="small" @click="savePermissions" :disabled="!currentRole">保存权限</el-button>
          </div>
          
          <div v-if="currentRole" class="permission-content">
            <!-- 菜单权限 -->
            <div class="permission-section">
              <h3>菜单权限</h3>
              <el-tree
                ref="menuTreeRef"
                :data="menuPermissions"
                :props="treeProps"
                show-checkbox
                node-key="id"
                :default-checked-keys="currentRole.menuPermissions"
                @check="handleMenuCheck"
              >
                <template #default="{ node, data }">
                  <span class="tree-node">
                    <el-icon v-if="data.icon"><component :is="data.icon" /></el-icon>
                    {{ data.label }}
                  </span>
                </template>
              </el-tree>
            </div>

            <!-- 操作权限 -->
            <div class="permission-section">
              <h3>操作权限</h3>
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="operation-group">
                    <h4>数据操作</h4>
                    <el-checkbox-group v-model="currentRole.dataPermissions">
                      <el-checkbox label="view">查看</el-checkbox>
                      <el-checkbox label="add">新增</el-checkbox>
                      <el-checkbox label="edit">编辑</el-checkbox>
                      <el-checkbox label="delete">删除</el-checkbox>
                      <el-checkbox label="export">导出</el-checkbox>
                      <el-checkbox label="import">导入</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="operation-group">
                    <h4>系统操作</h4>
                    <el-checkbox-group v-model="currentRole.systemPermissions">
                      <el-checkbox label="user-manage">用户管理</el-checkbox>
                      <el-checkbox label="role-manage">角色管理</el-checkbox>
                      <el-checkbox label="permission-manage">权限管理</el-checkbox>
                      <el-checkbox label="system-config">系统配置</el-checkbox>
                      <el-checkbox label="log-view">日志查看</el-checkbox>
                      <el-checkbox label="backup">数据备份</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </el-col>
              </el-row>
            </div>

            <!-- 数据权限 -->
            <div class="permission-section">
              <h3>数据权限</h3>
              <el-radio-group v-model="currentRole.dataScope">
                <el-radio label="all">全部数据</el-radio>
                <el-radio label="department">本部门数据</el-radio>
                <el-radio label="self">个人数据</el-radio>
                <el-radio label="custom">自定义数据</el-radio>
              </el-radio-group>
              
              <div v-if="currentRole.dataScope === 'custom'" class="custom-data-scope">
                <el-select
                  v-model="currentRole.customDataScope"
                  multiple
                  placeholder="请选择可访问的部门"
                  style="width: 100%; margin-top: 10px;"
                >
                  <el-option label="质检部" value="quality"></el-option>
                  <el-option label="生产部" value="production"></el-option>
                  <el-option label="采购部" value="purchase"></el-option>
                  <el-option label="销售部" value="sales"></el-option>
                  <el-option label="技术部" value="technology"></el-option>
                </el-select>
              </div>
            </div>
          </div>

          <div v-else class="no-role-selected">
            <el-empty description="请从左侧选择一个角色进行权限配置"></el-empty>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      :title="roleDialogTitle"
      width="500px"
      @close="resetRoleForm"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleFormRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveRole">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  HomeFilled, 
  DataAnalysis, 
  User, 
  Key, 
  Document, 
  Tickets,
  Edit,
  DocumentAdd
} from '@element-plus/icons-vue'

interface Role {
  id: number
  name: string
  userCount: number
  description: string
  status: string
  menuPermissions: number[]
  dataPermissions: string[]
  systemPermissions: string[]
  dataScope: string
  customDataScope: string[]
}

const currentRole = ref<Role | null>(null)
const menuTreeRef = ref()

const roleList = ref<Role[]>([
  {
    id: 1,
    name: '系统管理员',
    userCount: 2,
    description: '系统最高权限管理员',
    status: 'active',
    menuPermissions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    dataPermissions: ['view', 'add', 'edit', 'delete', 'export', 'import'],
    systemPermissions: ['user-manage', 'role-manage', 'permission-manage', 'system-config', 'log-view', 'backup'],
    dataScope: 'all',
    customDataScope: []
  },
  {
    id: 2,
    name: '质检员',
    userCount: 15,
    description: '负责质量检验工作',
    status: 'active',
    menuPermissions: [1, 5, 6, 7, 8],
    dataPermissions: ['view', 'add', 'edit'],
    systemPermissions: [],
    dataScope: 'department',
    customDataScope: []
  },
  {
    id: 3,
    name: '供应链主管',
    userCount: 5,
    description: '负责供应链管理',
    status: 'active',
    menuPermissions: [1, 9, 10],
    dataPermissions: ['view', 'add', 'edit', 'export'],
    systemPermissions: [],
    dataScope: 'department',
    customDataScope: []
  },
  {
    id: 4,
    name: '工艺工程师',
    userCount: 8,
    description: '负责工艺流程管理',
    status: 'active',
    menuPermissions: [1, 5, 6, 7],
    dataPermissions: ['view', 'edit'],
    systemPermissions: [],
    dataScope: 'department',
    customDataScope: []
  },
  {
    id: 5,
    name: '质量经理',
    userCount: 3,
    description: '负责质量管理工作',
    status: 'active',
    menuPermissions: [1, 2, 3, 4, 5, 6, 7, 8],
    dataPermissions: ['view', 'add', 'edit', 'delete', 'export'],
    systemPermissions: ['log-view'],
    dataScope: 'all',
    customDataScope: []
  }
])

const menuPermissions = ref([
  {
    id: 1,
    label: '首页',
    icon: 'HomeFilled',
    children: []
  },
  {
    id: 2,
    label: '质量数据管理',
    icon: 'DataAnalysis',
    children: []
  },
  {
    id: 3,
    label: '人员管理',
    icon: 'User',
    children: []
  },
  {
    id: 4,
    label: '权限管理',
    icon: 'Key',
    children: []
  },
  {
    id: 5,
    label: '质检标准',
    icon: 'Document',
    children: [
      {
        id: 6,
        label: '原材料质检标准',
        icon: 'Document'
      },
      {
        id: 7,
        label: '半成品质检标准',
        icon: 'Tickets'
      },
      {
        id: 8,
        label: '成品质检标准',
        icon: 'DataAnalysis'
      }
    ]
  },
  {
    id: 9,
    label: '供应链管理',
    icon: 'Edit',
    children: [
      {
        id: 10,
        label: '供应商质量',
        icon: 'DocumentAdd'
      }
    ]
  }
])

const treeProps = {
  children: 'children',
  label: 'label'
}

const roleDialogVisible = ref(false)
const roleDialogTitle = ref('新增角色')
const isEditRole = ref(false)
const roleFormRef = ref()

const roleForm = reactive({
  id: null,
  name: '',
  description: '',
  status: 'active'
})

const roleFormRules = {
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
}

const handleRoleChange = (role: Role) => {
  currentRole.value = { ...role }
  // 设置菜单权限选中状态
  setTimeout(() => {
    menuTreeRef.value?.setCheckedKeys(role.menuPermissions)
  }, 100)
}

const handleMenuCheck = (data: any, checked: any) => {
  if (currentRole.value) {
    currentRole.value.menuPermissions = checked.checkedKeys
  }
}

const addRole = () => {
  roleDialogTitle.value = '新增角色'
  isEditRole.value = false
  roleDialogVisible.value = true
}

const editRole = (role: Role) => {
  roleDialogTitle.value = '编辑角色'
  isEditRole.value = true
  Object.assign(roleForm, role)
  roleDialogVisible.value = true
}

const deleteRole = (role: Role) => {
  ElMessageBox.confirm(
    `确定要删除角色 ${role.name} 吗？删除后该角色下的用户将失去相应权限。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = roleList.value.findIndex(r => r.id === role.id)
    if (index > -1) {
      roleList.value.splice(index, 1)
      if (currentRole.value?.id === role.id) {
        currentRole.value = null
      }
    }
    ElMessage.success('删除成功')
  })
}

const saveRole = () => {
  roleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      if (isEditRole.value) {
        const index = roleList.value.findIndex(r => r.id === roleForm.id)
        if (index > -1) {
          Object.assign(roleList.value[index], roleForm)
        }
        ElMessage.success('角色更新成功')
      } else {
        const newRole = {
          ...roleForm,
          id: Date.now(),
          userCount: 0,
          menuPermissions: [],
          dataPermissions: [],
          systemPermissions: [],
          dataScope: 'department',
          customDataScope: []
        }
        roleList.value.push(newRole)
        ElMessage.success('角色创建成功')
      }
      roleDialogVisible.value = false
      resetRoleForm()
    }
  })
}

const resetRoleForm = () => {
  Object.assign(roleForm, {
    id: null,
    name: '',
    description: '',
    status: 'active'
  })
  roleFormRef.value?.resetFields()
}

const savePermissions = () => {
  if (!currentRole.value) return
  
  // 使用可选链操作符避免currentRole为null时的错误
  const index = roleList.value.findIndex(r => r.id === currentRole.value?.id)
  if (index > -1) {
    Object.assign(roleList.value[index], currentRole.value)
  }
  ElMessage.success('权限保存成功')
}



onMounted(() => {
  console.log('权限管理页面加载完成')
})
</script>

<style scoped>
.permission-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.page-header h2 {
  margin: 0;
  color: white;
}

.role-card,
.permission-card {
  background: white;
  min-height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  font-weight: bold;
  color: #333;
}

.permission-content {
  padding: 20px 0;
}

.permission-section {
  margin-bottom: 30px;
}

.permission-section h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}

.operation-group {
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 15px;
}

.operation-group h4 {
  margin: 0 0 10px 0;
  color: #666;
  font-size: 14px;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 5px;
}

.custom-data-scope {
  margin-top: 10px;
}

.no-role-selected {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

:deep(.el-checkbox) {
  margin-right: 0;
}
</style>